package com.example.task1.ui.AllService.EventManagement;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.task1.R;
import com.example.task1.application.MyApplication;
import com.example.task1.bean.EventCommentBean;
import com.example.task1.bean.EventDetailsBean;
import com.example.task1.http.Api;
import com.example.task1.util.ApiResp;
import com.example.task1.util.CallBack;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import retrofit2.Call;

public class EventDetailsActivity extends AppCompatActivity {

    private TextView tvTitle;
    private TextView tvTime;
    private TextView tvLike;
    private ImageView image;
    private TextView tvContent;
    private Button tvSave;
    private RecyclerView rvList;
    private EditText etInput;
    private Button btnSend;
    private int id;
    private TextView tvCommentNum;
    private int pageNum = 1;
    private boolean isTrue = true;
    private EventCommentAdapter eventCommentAdapter;
    private LinearLayoutManager linearLayoutManager;

    private void loadCommentList() {
        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (eventCommentAdapter.getItemCount() - 1 == linearLayoutManager.findLastVisibleItemPosition() && isTrue) {
                    isTrue = false;
                    getComment();
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_details);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setTitle("活动详情");
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        initView();
        id = getIntent().getIntExtra("id", 0);
        setAdapter();
        initData();
        getComment();
        loadCommentList();
        business();
    }

    private void business() {
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Call<ApiResp> apiRespCall = Api.api().get(MyApplication.TOKEN, "/prod-api/api/activity/signup/check?activityId=" + id);
                Api.send(apiRespCall, ApiResp.class, new CallBack<ApiResp>() {
                    @Override
                    public void success(ApiResp data) {
                        if (data.isSignup()) {
                            MyApplication.show(data.getMsg());
                        } else {
                            HashMap<String, Object> map = new HashMap<>();
                            map.put("activityId", id);
                            Call<ApiResp> apiRespCall = Api.api().post(MyApplication.TOKEN, "/prod-api/api/activity/signup", Api.getBody(map));
                            Api.send(apiRespCall, ApiResp.class, new CallBack<ApiResp>() {
                                @Override
                                public void success(ApiResp data) {
                                    MyApplication.show(data.getMsg());
                                }

                                @Override
                                public void error(String msg) {

                                }
                            });
                        }
                    }

                    @Override
                    public void error(String msg) {

                    }
                });
            }
        });
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = etInput.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    etInput.setError("评论不能为空");
                } else {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("activityId", id);
                    map.put("content", text);
                    EventCommentBean.RowsDTO rowsDTO = new EventCommentBean.RowsDTO();
                    rowsDTO.setNickName(MyApplication.user.getNickName());
                    rowsDTO.setUserName(MyApplication.user.getUserName());
                    rowsDTO.setAvatar(MyApplication.user.getAvatar());
                    rowsDTO.setContent(text);
                    rowsDTO.setCommentTime(new Date().toString());
                    List<EventCommentBean.RowsDTO> rowsDTOS = Arrays.asList(rowsDTO);
                    eventCommentAdapter.addData(rowsDTOS);
                    Call<ApiResp> post = Api.api().post(MyApplication.TOKEN, "/prod-api/api/activity/comment", Api.getBody(map));
                    Api.send(post, ApiResp.class, new CallBack<ApiResp>() {
                        @Override
                        public void success(ApiResp data) {
                            etInput.setText("");
                            MyApplication.show(data.getMsg());
                        }

                        @Override
                        public void error(String msg) {

                        }
                    });
                }
            }
        });
    }

    private void setAdapter() {
        eventCommentAdapter = new EventCommentAdapter();
        linearLayoutManager = new LinearLayoutManager(this);
        rvList.setAdapter(eventCommentAdapter);
        rvList.setLayoutManager(linearLayoutManager);
    }


    private void getComment() {
        Call<ApiResp> apiRespCall = Api.api().get(MyApplication.TOKEN, "/prod-api/api/activity/comment/list?activityId=" + id + "&pageNum=" + pageNum + "&pageSize=20");
        Api.send(apiRespCall, EventCommentBean.class, new CallBack<EventCommentBean>() {
            @Override
            public void success(EventCommentBean data) {
                tvCommentNum.setText(data.getTotal() + "条评论");
                if (eventCommentAdapter.getData().size() < data.getTotal()) {
                    pageNum++;
                    isTrue = true;
                    eventCommentAdapter.setData(data.getRows());
                } else {
                    MyApplication.show("没有更多数据了");
                }
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    private void initData() {
        Call<ApiResp> apiRespCall = Api.api().get(MyApplication.TOKEN, "/prod-api/api/activity/activity/" + id);
        Api.send(apiRespCall, EventDetailsBean.class, new CallBack<EventDetailsBean>() {
            @Override
            public void success(EventDetailsBean data) {
                EventDetailsBean.DataDTO rows = data.getData();
                MyApplication.glide(image, rows.getImgUrl());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Spanned spanned = Html.fromHtml(rows.getContent(), new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                try {
                                    Drawable drawable = Glide.with(EventDetailsActivity.this).load(source).submit().get();
                                    int intrinsicWidth = drawable.getIntrinsicWidth();
                                    int intrinsicHeight = drawable.getIntrinsicHeight();
                                    drawable.setBounds(0, 0, (1200 / intrinsicWidth) * intrinsicWidth, (1000 / intrinsicHeight) * intrinsicHeight);
                                    return drawable;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    return null;
                                }
                            }
                        }, null);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvContent.setText(spanned);
                            }
                        });
                    }
                }).start();
                tvLike.setText(rows.getLikeNum() + "人赞");
                tvTitle.setText(rows.getName());
                tvTime.setText(rows.getPublishTime());
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvLike = (TextView) findViewById(R.id.tv_like);
        image = (ImageView) findViewById(R.id.image);
        tvContent = (TextView) findViewById(R.id.tv_content);
        tvSave = (Button) findViewById(R.id.tv_save);
        rvList = (RecyclerView) findViewById(R.id.rv_list);
        etInput = (EditText) findViewById(R.id.et_input);
        btnSend = (Button) findViewById(R.id.btn_send);
        tvCommentNum = (TextView) findViewById(R.id.tv_commentNum);
    }
}